package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.Admin;
import com.xmy.cultivate.entity.CodeVersion;
import com.xmy.cultivate.entity.CodeVersionAdminSee;
import com.xmy.cultivate.entity.RoleAdmin;
import com.xmy.cultivate.service.IAdminService;
import com.xmy.cultivate.service.ICodeVersionAdminSeeService;
import com.xmy.cultivate.service.ICodeVersionService;
import com.xmy.cultivate.service.IRoleAdminService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/codeVersion")
public class CodeVersionController extends BaseController {

    @Lazy
    final
    ICodeVersionService iCodeVersionService;

    @Autowired
    IAdminService iAdminService;

    @Autowired
    ICodeVersionAdminSeeService iCodeVersionAdminSeeService;

    @Autowired
    IRoleAdminService iRoleAdminService;

    public CodeVersionController(ICodeVersionService iCodeVersionService) {
        this.iCodeVersionService = iCodeVersionService;
    }

    @GetMapping("getCodeVersion")
    @ApiOperation("查询版本管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "releaseTime", value = "发布时间", dataType = "String"),
            @ApiImplicitParam(name = "terminalState", value = "角色id，多个逗号分开", dataType = "String"),
            @ApiImplicitParam(name = "state", value = "0待发布；1已发布；2已撤回", dataType = "String")
    })
    public Result index(@RequestParam Map<String, Object> reMap) {
        int pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.parseInt((String) reMap.get("pageNum"));
        int pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.parseInt((String) reMap.get("pageSize"));
        Page<CodeVersion> iPage = new Page<>(pageNum, pageSize);
        String state = (String) reMap.get("state");
        String releaseTime = (String) reMap.get("releaseTime");
        String terminalState = (String) reMap.get("terminalState");
        QueryWrapper<CodeVersion> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(releaseTime)) {
            queryWrapper.between("release_time", releaseTime, releaseTime + " 23:59:59");//发布时间
        }
        if (StringUtils.isNotBlank(terminalState)) {
            String[] terminalStateArr = terminalState.split(",");
            queryWrapper.and(q -> {
                for (String s : terminalStateArr) {
                    q.like("terminal_state", s).or();
                }
            });//角色id，多个逗号分开
        }
        queryWrapper.eq(StringUtils.isNotBlank(state),"state",state);// 0待发布；1已发布；2已撤回
        queryWrapper.orderByDesc("id");
        iCodeVersionService.page(iPage, queryWrapper);
        return new Result(Code.OK, new PageResult<>(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), "查询版本管理~");
    }

    @PostMapping("/addCodeVersion")
    @ApiOperation("添加版本管理信息")
    public Result addCodeVersion(@RequestBody CodeVersion codeVersion){
        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);
        codeVersion.setReleaseTime(nowDateTime);
        iCodeVersionService.save(codeVersion);
        if (codeVersion.getState() == 1) editSeeVersion(codeVersion);
        return new Result(Code.OK,"","添加版本管理成功");
    }

    private void editSeeVersion(CodeVersion codeVersion) {
        //查询角色管理员
        if (codeVersion.getTerminalState() != null) {
            UpdateWrapper<CodeVersionAdminSee> codeVersionAdminSeeUpdateWrapper = new UpdateWrapper<>();
            QueryWrapper<RoleAdmin> roleAdminQueryWrapper = new QueryWrapper<>();
            roleAdminQueryWrapper.in("role_id", codeVersion.getTerminalState().split(","));
            roleAdminQueryWrapper.groupBy("admin_id");
            List<RoleAdmin> roleAdminList = iRoleAdminService.list(roleAdminQueryWrapper);
            ArrayList<Long> adminIdArr = new ArrayList<>();
            QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
            adminQueryWrapper.eq("is_super",1);
            List<Admin> adminList = iAdminService.list(adminQueryWrapper);
            if (!adminList.isEmpty()) {
                for (Admin admin: adminList) {
                    adminIdArr.add(admin.getId());
                }
            }
            if (!roleAdminList.isEmpty()) {
                for (RoleAdmin roleAdmin : roleAdminList) {
                    adminIdArr.add(roleAdmin.getAdminId());
                }
            }
            if (!adminIdArr.isEmpty()) {
                codeVersionAdminSeeUpdateWrapper.in("admin_id", adminIdArr);//区分角色权限
            }
            codeVersionAdminSeeUpdateWrapper.eq("1",1);
            codeVersionAdminSeeUpdateWrapper.set("see_version",0);
            iCodeVersionAdminSeeService.update(codeVersionAdminSeeUpdateWrapper);
        }
    }
    @PostMapping("/editCodeVersion")
    @ApiOperation("修改版本管理信息")
    public Result editCodeVersion(@RequestBody CodeVersion codeVersion){
        CodeVersion codeVersionServiceById = iCodeVersionService.getById(codeVersion.getId());
        if (codeVersionServiceById.getState() == 1) {
            return new Result(Code.ERROR, "", "当前状态不允许修改信息，请改为撤回状态后进行修改！！！");
        }
        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);
        codeVersion.setReleaseTime(nowDateTime);
        boolean b = iCodeVersionService.updateById(codeVersion);
        if (b) {
            if (codeVersion.getState() == 1) editSeeVersion(codeVersion);
            return new Result(Code.OK, "", "修改版本管理信息成功");
        } else {
            return new Result(Code.ERROR, "", "修改版本管理信息失败");
        }
    }

    @PostMapping("/editCodeVersionState")
    @ApiOperation("修改版本管理状态：0待发布；1已发布；2已撤回")
    public Result editCodeVersionState(@RequestBody CodeVersion codeVersion){
        CodeVersion codeVersionServiceById = iCodeVersionService.getById(codeVersion.getId());
        codeVersionServiceById.setState(codeVersion.getState());
        boolean b = iCodeVersionService.updateById(codeVersionServiceById);
        if (b) {
            return new Result(Code.OK, "", "修改版本管理状态成功");
        } else {
            return new Result(Code.ERROR, "", "修改版本管理状态失败");
        }
    }

    @DeleteMapping("/deleteCodeVersion")
    @ApiOperation("删除版本管理")
    public Result deleteCodeVersion(@RequestParam Map<String, Object> reMap){
        if (reMap.get("id") != null && !reMap.get("id").toString().isEmpty()) {
            boolean b = iCodeVersionService.removeById(Long.valueOf(reMap.get("id").toString()));
            if (b) {
                return new Result(Code.OK, "", "删除版本管理成功");
            }
        }
        return new Result(Code.ERROR, "", "删除版本管理失败");
    }

    @GetMapping("getCodeVersionTen")
    @ApiOperation("查询版本管理最新发布十条")
    public Result getCodeVersionTen() {
        QueryWrapper<CodeVersion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state",1);// 0待发布；1已发布；2已撤回
        if (this.adminModel.getIsSuper() == 0) {
            QueryWrapper<RoleAdmin> roleAdminQueryWrapper = new QueryWrapper<>();
            roleAdminQueryWrapper.eq("admin_id", this.adminId);
            List<RoleAdmin> roleAdminList = iRoleAdminService.list(roleAdminQueryWrapper);
            if (!roleAdminList.isEmpty()) {
                queryWrapper.and(q -> {
                    for (RoleAdmin roleAdmin : roleAdminList) {
                        q.like("terminal_state",roleAdmin.getRoleId()).or();
                    }
                });
            } else {
                return new Result(Code.OK, "", "查询版本管理最新发布十条~");
            }
        }
        queryWrapper.orderByDesc("release_time");
        queryWrapper.last("LIMIT 10");
        List<CodeVersion> list = iCodeVersionService.list(queryWrapper);
        return new Result(Code.OK, list, "查询版本管理最新发布十条~");
    }
}
